<template>
  <el-popover
    v-model="showPopover"
    :disabled="disabled"
    placement="bottom"
    width="700"
    popper-class="no-padding-popover"
    trigger="click">

    <relative-card
      v-model="showPopover"
      :relative-type="formType"
      :request-config="requestConfig"
      :label="`选择${typeObj.name}`"
      :primary-key="typeObj.primaryKey"
      :default-value="dataValue"
      radio
      @close="showPopover = !showPopover"
      @confirm="handleRelativeConfirm" />

    <flexbox
      slot="reference"
      :class="[disabled ? 'is_disabled' : 'is_valid']"
      wrap="wrap"
      class="user-container xh-form-border"
      @click.native="contentClick">
      <div
        v-for="(item, index) in dataValue"
        :key="index"
        class="user-item"
        @click.stop="deleteItem(index)">{{ getShowName(item) }}
        <i class="delete-icon el-icon-close"/>
      </div>
      <div
        v-if="dataValue.length === 0"
        class="add-item">
        +添加
      </div>
    </flexbox>
  </el-popover>
</template>

<script>
/**
 * Create by yxk at 2020/6/10
 */
import {
  jxcFieldQueryPageListAPI,
  jxcFieldQueryListHeadAPI,
  crmCustomerPageListAPI,
  crmFieldCustomerQueryListHeadAPI
} from '@/api/jxc/field'
import { jxcWarehouseQueryListAPI } from '@/api/jxc/warehouse'
// import { crmCustomerIndexAPI } from '@/api/crm/customer'
// import { filedGetTableFieldAPI } from '@/api/crm/common'

import RelativeCard from '../../RelativeCard'
import JxcTypes from '../../../jxcTypes'
import { isObject } from '@/utils/types'

export default {
  name: 'RelativeChoose',
  components: {
    RelativeCard
  },
  props: {
    value: {
      type: [String, Number, Object, Array],
      default: null
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    },
    // 字段类型
    formType: {
      type: String,
      required: true
    },
    // 字段数据源
    field: {
      type: Object,
      default: () => {}
    },
    // 关联项请求附加参数
    params: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      showPopover: false,

      dataValue: []
    }
  },
  computed: {
    typeObj() {
      if (this.formType === 'customer') {
        return {
          name: '客户',
          primaryKey: 'customerId'
        }
      }
      const type = {
        supplier_cause: 'jxc_supplier',
        purchase_cause: 'jxc_purchase',
        sale_cause: 'jxc_sale',
        salereturn_cause: 'jxc_salereturn',
        retreat_cause: 'jxc_retreat',
        warehouse_cause: 'jxc_warehouse'
      }[this.formType]

      return JxcTypes[type]
    },

    // 请求配置
    requestConfig() {
      let fieldRequest = null
      let fieldParams = {}
      let fieldList = null
      let placeholder = ''

      let listRequest = null
      let listParams = {}

      let searchParamsFn = function(params, keyword) {
        if (keyword) {
          params = {
            ...params,
            search: keyword
          }
        }
        return params
      }
      if (this.formType === 'warehouse_cause') {
        searchParamsFn = function(params, keyword) {
          return {
            ...params,
            warehouseName: keyword
          }
        }
      }

      if (this.formType === 'supplier_cause') {
        // 供应商
        fieldParams = {
          label: JxcTypes.jxc_supplier.label
        }
        listParams = {
          label: JxcTypes.jxc_supplier.label,
          ...this.params
        }
        fieldRequest = jxcFieldQueryListHeadAPI
        listRequest = jxcFieldQueryPageListAPI
      } else if (this.formType === 'purchase_cause') {
        // 采购单
        fieldParams = {
          label: JxcTypes.jxc_purchase.label
        }
        listParams = {
          label: JxcTypes.jxc_purchase.label,
          ...this.params
        }
        fieldRequest = jxcFieldQueryListHeadAPI
        listRequest = jxcFieldQueryPageListAPI
      } else if (this.formType === 'sale_cause') {
        // 销售订单
        fieldParams = {
          label: JxcTypes.jxc_sale.label
        }
        listParams = {
          label: JxcTypes.jxc_sale.label,
          ...this.params
        }
        fieldRequest = jxcFieldQueryListHeadAPI
        listRequest = jxcFieldQueryPageListAPI
      } else if (this.formType === 'salereturn_cause') {
        // 销售退货订单
        fieldParams = {
          label: JxcTypes.jxc_salereturn.label
        }
        listParams = {
          label: JxcTypes.jxc_salereturn.label,
          ...this.params
        }
        fieldRequest = jxcFieldQueryListHeadAPI
        listRequest = jxcFieldQueryPageListAPI
      } else if (this.formType === 'warehouse_cause') {
        // 仓库
        fieldList = [
          { fieldName: 'warehouseName', name: '仓库名称' },
          { fieldName: 'warehouseCode', name: '仓库编码' },
          { fieldName: 'warehouseAddress', name: '仓库地址' },
          { fieldName: 'createUserName', name: '创建人' },
          { fieldName: 'createTime', name: '创建时间' },
          { fieldName: 'updateTime', name: '更新时间' }
        ]
        placeholder = '请输入仓库名称'
        listRequest = jxcWarehouseQueryListAPI
      } else if (this.formType === 'customer') {
        fieldRequest = crmFieldCustomerQueryListHeadAPI
        fieldParams = {
          label: 2
        }
        listRequest = crmCustomerPageListAPI
        listParams = {
          label: 2
        }
      } else if (this.formType === 'retreat_cause') {
        // 采购退货单
        fieldParams = {
          label: JxcTypes.jxc_retreat.label
        }
        listParams = {
          label: JxcTypes.jxc_retreat.label,
          ...this.params
        }
        fieldRequest = jxcFieldQueryListHeadAPI
        listRequest = jxcFieldQueryPageListAPI
      }

      return {
        fieldRequest: fieldRequest,
        fieldParams: fieldParams,
        fieldList: fieldList,
        listRequest: listRequest,
        listParams: listParams,
        placeholder: placeholder,
        searchParamsFn: searchParamsFn
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        // this.getShowName(val)
        if (!val) {
          this.dataValue = []
          this.emitChange({
            valData: [],
            data: []
          })
        } else if (isObject(val)) {
          this.dataValue = [val]
          this.emitChange({
            valData: [val.id],
            data: [val.id]
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleRelativeConfirm(data) {
      this.dataValue = data.data
      this.showPopover = false
      this.emitChange(data)
    },

    contentClick() {
    },

    deleteItem(index) {
      if (this.disabled) return
      this.dataValue.splice(index, 1)
      this.emitChange({
        valData: this.dataValue.map(o => o[this.typeObj.primaryKey]),
        data: this.dataValue
      })
    },

    emitChange(data) {
      this.$emit('input', data.valData.join(','))
      this.$emit('change', this.field, data)
    },

    getShowName(item) {
      const keyMap = {
        supplier_cause: 'supplierName',
        purchase_cause: 'orderNumber',
        warehouse_cause: 'warehouseName',
        sale_cause: 'orderNumber',
        customer: 'customerName',
        retreat_cause: 'orderNumber',
        salereturn_cause: 'orderNumber'
      }
      return item[keyMap[this.formType]] || item.name
    }
  }
}
</script>

<style scoped lang="scss">
  .user-container {
    min-height: 34px;
    position: relative;
    border-radius: 3px;
    font-size: 12px;
    border: 1px solid #ddd;
    color: #333333;
    line-height: 15px;
    cursor: pointer;
    margin: 3px 0;
    .user-item {
      padding: 5px;
      background-color: #e2ebf9;
      border-radius: 3px;
      margin: 3px;
      cursor: pointer;
    }
    .add-item {
      padding: 5px;
      color: $xr-color-text-placeholder;
      cursor: pointer;
    }
    .delete-icon {
      color: #999;
      cursor: pointer;
    }
  }

  .user-container.is_disabled {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    cursor: not-allowed;
    .user-item {
      background-color: #f0f4f8ea;
      color: #c0c4cc;
      cursor: not-allowed;
    }
    .delete-icon {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    .add-item {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  .user-container.is_valid:hover {
    border-color: #c0c4cc;
  }
</style>
